package com.ying.myrabbitmq.config;

import com.ying.myrabbitmq.user.OrderEntity;
import org.springframework.amqp.core.*;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.HashMap;

@Configuration
public class MyMQConfig {

    @RabbitListener(queues = "order.release.order.queue")
    public void listener(OrderEntity orderEntity, Channel channel, Message message) throws IOException {
        /**
         * 监听过期后的订单
         */
        System.out.println("收到过期订单，订单号--->" + orderEntity.getOrdernumber());
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

    }


    @Bean
    public Queue orderDelayQueue() {

        HashMap<String, Object> arguments = new HashMap<>();
        /**
         *  1、创建名称为order.delay.queue的延迟队列
         *  arguments.put("x-dead-letter-exchange", "order.delay.queue");
         *  2、设置过期时间
         *  arguments.put("x-message-tt1", 60000);
         *  3、过期后交给之前发给他的交换机，重新设置路由键，在路由到处理过期订单的队列
         *  arguments.put("x-dead-letter-routing-key", "order.release.order");
         */

        arguments.put("x-dead-letter-exchange", "order-event-exchange");
        arguments.put("x-dead-letter-routing-key", "order.release.order");
        arguments.put("x-message-ttl", 20000);
        return new Queue("order.delay.queue", true, false, false, arguments);
    }

    @Bean
    public Queue orderReleaseOrderQueue() {
        /**
         * 用来处理过期订单的队列
         */
        return new Queue("order.release.order.queue", true, false, false);
    }

    @Bean
    public Exchange orderEventExchange() {
        /**
         * 创建订单需要发送的交换机
         */
        return new TopicExchange("order-event-exchange", true, false);
    }

    @Bean
    public Binding orderCreateOrderBingding() {
        /**
         * 用户下单后通过路由键路由给延迟订单队列，锁定库存
         */
        return new Binding("order.delay.queue",
                Binding.DestinationType.QUEUE,
                "order-event-exchange",
                "order.create.order",
                null);
    }

    @Bean
    public Binding orderReleaseOrderBingding() {
        /**
         * 当订单过期后路由到处理过期订单的队列
         */
        return new Binding("order.release.order.queue",
                Binding.DestinationType.QUEUE,
                "order-event-exchange",
                "order.release.order",
                null);
    }
}
